<template>
  <div class="l-rblock">
    <l-data-list
      :columns="data.columns"
      :isMore="!!data.moduleId"
      :label="data.label"
      :data="dataSource"
      @more="handleMore"
      @itemClick="handleClick"
    ></l-data-list>

    <template v-if="isLoad">
      <l-dialog
        v-if="isDialog"
        :title="$t(formTitle)"
        :visible.sync="formVisible"
        :height="dialogHeight"
        :width="dialogWidth"
        :hasBtns="false"
        @closed="handleCloseForm"
        @opened="handleOpenedForm"
      >
        <l-form-viewer ref="form" :formInfo="formScheme.formInfo" :isAuth="true" :isRead="true"></l-form-viewer>
      </l-dialog>
      <l-drawer
        v-else
        :title="$t(formTitle)"
        :visible.sync="formVisible"
        :width="drawerWidth"
        :showOk="false"
        :showClose="false"
        @closed="handleCloseForm"
        @opened="handleOpenedForm"
      >
        <l-form-viewer ref="form" :formInfo="formScheme.formInfo" :isAuth="true" :isRead="true"></l-form-viewer>
      </l-drawer>
    </template>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
const apiScheme = window.$api.custmerForm.scheme;
export default {
  props: ["data", "isPreview"],
  data() {
    return {
      isLoad: false,
      formSchemeId: "",
      formScheme: null,
      formTitle: "",
      formVisible: false,
      formEditRow: null,

      // 主表数据
      mainTable: null,
      mainTableIndex: 0,
    };
  },
  asyncComputed: {
    dataSource: {
      async get() {
        const { f_Scheme, f_Id } = (await this.$awaitWraper(apiScheme.getHistory(this.data.formVerison))) || {};
        this.formScheme = JSON.parse(f_Scheme);
        this.formSchemeId = f_Id;
        if (this.data.orderId && this.data.formVerison && this.data.viewForm) {
          if (this.formType == 2) {
            const apiGet = this.formScheme.db.find((item) => item.apiType == 0);
            const api = await this.$awaitWraper(apiScheme.apiParams(`${this.apiUrl}data/datainterface/${apiGet.f_Id}`));
            let params = {
              rows: this.data.limitRow == 1 ? this.data.maxRows : 100000,
              page: 1,
              sidx: this.data.orderId,
            };
            const data = (await this.$awaitWraper(apiScheme.apiParams(api.f_Url, api.f_RequestMethod, params))) || {};
            return data.rows || [];
          } else {
            const queryData = {
              paginationInputDto: {
                rows: this.data.limitRow == 1 ? this.data.maxRows : 100000,
                page: 1,
                sidx: this.data.orderId,
              },
            };
            const data =
              (await this.$awaitWraper(apiScheme.getDataPage(this.data.moduleId, this.data.formVerison, queryData))) ||
              {};
            //console.log(this.data,'dataSource')
            return data.rows || [];
          }
        } else {
          return [];
        }
      },
    },
  },
  computed: {
    ...mapGetters(["modules"]),

    isDialog() {
      return this.formScheme.formInfo.openType != "2";
    },
    dialogHeight() {
      return this.formScheme.formInfo.dialogHeight || 600;
    },
    dialogWidth() {
      return this.formScheme.formInfo.dialogWidth || 800;
    },

    drawerWidth() {
      return this.formScheme.formInfo.drawerWidth || 600;
    },
    formType() {
      return this.formScheme.formType;
    },
    primaryKey() {
      return this.formScheme.primaryKey;
    },
  },
  methods: {
    handleMore() {
      if (!this.isPreview && this.data.moduleId) {
        const module = this.modules.find((t) => t.f_ModuleId == this.data.moduleId);
        if (module) {
          this.$router.$lrRouter.goto(module);
        }
      }
    },
    async handleClick(row) {
      const loading = this.$loading({
        lock: true,
        text: "加载表单中...",
        spinner: "el-icon-loading",
      });

      await this.initForm();
      loading.close();

      this.formEditRow = row;
      this.showForm("查看详情");
    },
    async initForm() {
      if (!this.isLoad) {
        if (!this.formScheme) {
          const { f_Scheme, f_Id } = (await this.$awaitWraper(apiScheme.getHistory(this.data.formVerison))) || {};
          this.formScheme = JSON.parse(f_Scheme);
          this.formSchemeId = f_Id;
        }

        // 主表
        this.mainTableIndex = this.formScheme.db.findIndex((t) => t.type == "main");
        this.mainTable = this.formScheme.db[this.mainTableIndex];

        this.isLoad = true;
      }
    },
    handleCloseForm() {
      this.$refs.form.resetFormData();
    },
    handleOpenedForm(showLoading, hideLoading) {
      showLoading("加载数据中");
      this.$nextTick(async () => {
        if (this.formType == 2) {
          const apiForm = this.formScheme.db.find((item) => item.apiType == 1);
          const api = await this.$awaitWraper(apiScheme.apiParams(`${this.apiUrl}data/datainterface/${apiForm.f_Id}`));
          const res = await this.$awaitWraper(
            apiScheme.apiParams(`${api.f_Url}/${this.formEditRow[this.primaryKey]}`, "get")
          );
          this.$refs.form.init(this.turnApiDataForm(res));
        } else if (this.formScheme.formType == 1) {
          let formdata = {};
          formdata[this.mainTable.name] = [this.formEditRow];
          const mainDataQuery = {};
          if (this.formScheme.db.length > 0) {
            this.formScheme.db.forEach((db) => {
              mainDataQuery[db.relationField] = this.formEditRow[db.relationField];
            });
            const res = await this.$awaitWraper(
              apiScheme.getViewData(this.formSchemeId, { mainData: JSON.stringify(mainDataQuery) })
            );
            formdata = {
              ...formdata,
              ...res,
            };
          }
          this.$refs.form.init(formdata);
        } else {
          const mainTablePk = this.formScheme.primaryKey;
          const data = await this.$awaitWraper(
            apiScheme.getData(this.formSchemeId, {
              key: mainTablePk,
              keyValue: this.formEditRow[`${mainTablePk.toLowerCase()}0`],
            })
          );
          this.$refs.form.init(data);
        }
        hideLoading();
      });
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
    turnApiDataForm(data) {
      let formdata = {};
      if (Object.prototype.toString.call(data) == "[object Object]") {
        const mainTable = Object.keys(data).filter((key) => {
          return !(Object.prototype.toString.call(data[key]) == "[object Object]" || Array.isArray(data[key]));
        });

        if (mainTable.length) {
          const mainData = mainTable.reduce((acc, crr) => {
            acc[crr.toLowerCase()] = data[crr];
            return acc;
          }, {});
          formdata = {
            root: [mainData],
          };
        }

        const childTable = Object.keys(data).filter((key) => {
          return Object.prototype.toString.call(data[key]) == "[object Object]" || Array.isArray(data[key]);
        });

        childTable.forEach((key) => {
          formdata[key.toLowerCase()] = [this.turnToLowerCase(data[key])];
        });
      }
      return formdata;
    },
  },
};
</script>
